<?php
/**
 * Mysql 数据库操作类
 *
 */
class Mysql {

	public $db_server;
	public $db_user;
	public $db_passwd;
	public $db_name;
	public $db_charset = "utf8";
	public $conn = FALSE;
	
	/**
	 * 构选函数，实例化时自动连接数据库
	 *
	 */	
	function __construct($db_server, $db_user, $db_passwd, $db_name, $db_charset){
		
		$this->db_server = $db_server;
		$this->db_user = $db_user;
		$this->db_passwd = $db_passwd;
		$this->db_name = $db_name;
		$this->db_charset = $db_charset;

		$this->open_connect();
	}

	/**
	 * 连接数据库
	 *
	 */
	function open_connect()
	{
	
		$this->conn = @mysql_connect($this->db_server, $this->db_user, $this->db_passwd);
		if($this->conn == false){
			die('无法连接数据库服务器！');
		}
		
		//mysql_query("set names utf8");
		mysql_set_charset($this->db_charset);
		
		$db_select = mysql_select_db($this->db_name, $this->conn);	
		if(!$db_select){
			die('选择数据库 '. $this->db_name .' 失败!');
		}	
	
	}
	
	/**
	 * 关闭连接
	 *
	 */	
	function close(){
		if(isset($this->conn)){
			mysql_close($this->conn);
		}
	}
	
	/**
	 * 发送查询语句
	 *
	 */	
	function query($sql){
	
		if(empty($sql)) return false;
		if(!$this->conn) return false;
		
		return @mysql_query($sql, $this->conn);
	}
	
	/**
	 * 提取一条记录
	 *
	 */		
	function fetch_one($result){
        if($result && $this->num_rows($result)){
            return mysql_fetch_assoc($result);
        }

	}	
	
	/**
	 * 提取多条记录
	 *
	 */		
	function fetch_all($result){
		
		$data = array();
		if($result && $this->num_rows($result)){
            while ($row = mysql_fetch_assoc($result)){
                $data[] = $row;
            }
            return $data;
        }
	}

	/**
	 * 返回记录数
	 *
	 */		
	function num_rows($result)
	{
		return mysql_num_rows($result);
	}

	/**
	 * 返回新添加记录 id
	 *
	 */	
	function insert_id(){
		return mysql_insert_id($this->conn);
	}	
	
	/**
	 * 返回影响的记录数
	 *
	 */
	function affected_rows(){
		return mysql_affected_rows($this->conn);
	}

}

?>